package com.lxq.market.util;

import java.sql.*;

public class JDBCUtil {
    private static String user="root";
    private static String password="123456";
    private static String url="jdbc:mysql://localhost:3306/app_market?autoReconnect=true";
    private static Connection connection;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //连接数据库，返回Connection
    public static Connection getConnection() {
        if (connection!=null)return connection;
        try {
            connection=DriverManager.getConnection(url, user, password);
            return connection;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static ResultSet execQuery(String sql,Object... param){
        Connection connection = getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            if (param!=null){
                int index=1;
                for (Object paramObj : param) {
//                    String typeName = paramObj.getClass().getTypeName();
                    preparedStatement.setObject(index,paramObj.toString());
                    index++;
//                    switch (typeName){
//                        case "java.lang.String":
//
//                            break;
//                        case "int":
//                            break;
//                        case "double":break;
//                    }
                }
            }
            return preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean execSQL(String sql,Object... param){
        Connection connection = getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            if (param!=null){
                int index=1;
                for (Object paramObj : param) {
                    preparedStatement.setObject(index,paramObj.toString());
                    index++;
                }
            }

            return preparedStatement.executeUpdate() == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    //关闭相关连接
    //有需要关闭的就传入对象，没有就传入null
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        //判断是否传入为null
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
